<!DOCTYPE html>
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <title>打印</title>
  <script type='text/javascript' src='../../../../../../supcan/binary/dynaload.js?20'></script>
</head>

<script>
  function OnReady(id) {
    let result = AF.func('ReadSheet', $XML)
    console.log(result)
    let view = AF.func('CallFunc', 18)
  }

  window.startPrint = (data) => {
    AF.func('ReadSheet', data)
    AF.func('CallFunc', 18)
  }
  function OnEvent(id, event, p1, p2, p3, p4) {
			console.log(id)
			console.log(event)
		}
</script>

<body>
  <div style="width: 100px;height: 100px;">
    <script>
      try{
        insertReport('AF', 'Border=single,3D; Ruler=Horz; Rebar=Print,Property,Font; print=11, 216')
      }catch(err){
        console.error(err);
      }
    </script>
  </div>
</body>
<script>
  var $XML = '<?xml version="1.0" encoding="UTF-8" ?>'
  function dealFontSize(size) {
    let result = ''
    switch (size) {
      case 9:
        result = -12
        break
      case 10:
        result = -13
        break
      case 11:
        result = -15
        break
      case 12:
        result = -16
        break
      case 13:
        result = -17
        break
      case 14:
        result = -19
        break
      case 16:
        result = -21
        break
      case 18:
        result = -24
        break
      case 20:
        result = -27
        break
      case 22:
        result = -29
        break
      case 24:
        result = -32
        break
      case 26:
        result = -35
        break
      case 28:
        result = -37
        break
      case 36:
        result = -48
        break
      case 48:
        result = -64
        break
      case 72:
        result = -96
        break
      default:
        result = -14
    }
    return result
  }
  function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  }
  function convertToFullColorCode(colorCode) {
    // 使用正则表达式提取颜色代码中的每个字符
    const regex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    const matches = colorCode.match(regex);

    // 如果匹配到了 3 个字符，则将其每个字符重复一遍
    if (matches) {
      return `#${matches[1]}${matches[1]}${matches[2]}${matches[2]}${matches[3]}${matches[3]}`;
    }

    // 如果颜色代码格式不正确，则直接返回原来的代码
    return colorCode;
  }
  function dealTD(item, index) {
    let d = item.v
    let textColor = ''
    let align = ''
    let vAlign = ''
    let fontIndex = ''
    let leftBorderColor = ''
    let topBorderColor = ''
    let bgColor = ''
    let AutoBreakLine = ''
    let topBorder = ''
    let leftBorder = ''
    if (d.fc) {
      if (d.fc.indexOf('rgb') != -1) {
        let reg = /([0-9]+)/g
        let arr = d.fc.match(reg)
        d.fc = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
      } else if (d.fc.indexOf('#') != -1) {
        d.fc = convertToFullColorCode(d.fc)
      }
      textColor = ` textColor="${d.fc}"`
    }
    if (d.bg) {
      if (d.bg.indexOf('rgb') != -1) {
        let reg = /([0-9]+)/g
        let arr = d.bg.match(reg)
        d.bg = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
      } else if (d.bg.indexOf('#') != -1) {
        d.bg = convertToFullColorCode(d.bg)
      }
      bgColor = ` bgColor="${d.bg}"`
    }
    if (d.ht == 0) {
      align = ' align="center"'
    } else if (d.ht == 2) {
      align = ' align="right"'
    }
    if (d.vt == 2) {
      vAlign = ' vAlign="bottom"'
    } else if (d.vt == 1) {
      vAlign = ' vAlign="top"'
    }
    if (index == 0) {
      fontIndex = ''
    } else {
      fontIndex = ` fontIndex="${index}"`
    }
    if (d.border) {
      if (d.border.leftBorderColor) {
        leftBorderColor = ` leftBorderColor="${d.border.leftBorderColor}"`
      }
      if (d.border.topBorderColor) {
        topBorderColor = ` topBorderColor="${d.border.topBorderColor}"`
      }
      if (d.border.topBorder && d.border.topBorder != 1) {
        topBorder = ` topBorder="${d.border.topBorder}"`
      }
      if (d.border.leftBorder && d.border.leftBorder != 1) {
        leftBorder = ` leftBorder="${d.border.leftBorder}"`
      }
    }
    if (d.tb == 2) {
      AutoBreakLine = ` AutoBreakLine="3"`
    }
    if (d.m) {
      return `<TD col="${item.c}"${fontIndex}${leftBorder}${topBorder}${textColor}${align}${vAlign}${leftBorderColor}${topBorderColor}${bgColor}${AutoBreakLine}>${d.m}</TD>`
    } else {
      return `<TD col="${item.c}"${fontIndex}${leftBorder}${topBorder}${textColor}${align}${vAlign}${leftBorderColor}${topBorderColor}${bgColor}${AutoBreakLine} />`
    }
  }
  function toXml(data) {
    let $XML = '<?xml version="1.0" encoding="UTF-8" ?>'
    $XML += '\n<Report>\n'
    $XML += '\t<WorkSheet name="Sheet">\n'
    $XML += '\t\t<Properties>\n'
    $XML += '\t\t\t<BackGround bgColor="#FFFFFF" />\n'
    $XML += '\t\t\t<DefaultTD>\n'
    $XML += '\t\t\t\t<TD fontIndex="0" textColor="#000000" transparent="true" leftBorder="1" topBorder="1" leftBorderColor="#C0C0C0" topBorderColor="#C0C0C0" decimal="2" align="left" vAlign="middle" isProtected="false" isThousandSeparat="true" datatype="0" isRound="true" isPrint="true" />\n'
    $XML += '\t\t\t</DefaultTD>\n'
    $XML += '\t\t\t<Other isShowZero="true" isRefOri="true" AutoBreakLine="1" Ellipsis="1" LineDistance="0" isRowHeightAutoExtendAble="true" />\n'
    $XML += '\t\t</Properties>\n'


    // let data = res.content[0]
    console.log(data)
    // 列宽数组
    let columns = []
    data.visibledatacolumn.reduce((pre, cur) => {
      columns.push(cur - pre)
      return cur
    }, 0)
    // 行高数组
    let rows = []
    data.visibledatarow.reduce((pre, cur) => {
      rows.push((cur - pre) * 4 / 3)
      return cur
    }, 0)
    // let fonts = ['<Font faceName="Microsoft YaHei UI" charSet="134" height="-14" weight="400" />']
    let fonts = [{
      faceName: 'Times New Roman',
      // charSet: 134,
      height: '-14',
      weight: '400',
      pitchAndFamily: 18,
      quality: 1,
      outPrecision: 3,
      clipPrecision: 2
    }]
    let obj = {}
    // 如果设置了溢出，进行拆分
    data.celldata.forEach((item, index) => {
      let d = item.v
      // 处理文字溢出，换行
      if (d.tb == 1) {
        // 溢出
        // console.log(item)
        // 如果当前单元格设置了合并单元格或者单元格无内容，则不处理
        if ((d.mc && (d.mc.cs > 0 || d.mc.rs > 0)) || !d.m) {

        } else {
          let maxCount = Math.ceil((columns[item.c] * 0.75 / (d.fs || 10.5)) * 2)
          let charCount = 0
          let text = d.m
          for (let i = 0; i < d.m.length; i++) {
            let a = text.charAt(i)
            if (a.match(/[^\x00-\xff]/ig) != null) {
              charCount += 2
            } else {
              charCount += 1
            }
          }
          let cs = item.c
          let currentCol = item.c
          while (charCount > maxCount && data.data[item.r][currentCol + 1] && !data.data[item.r][currentCol + 1].m) {
            console.log('99999')
            cs++
            charCount -= maxCount
            currentCol++
            maxCount = Math.ceil((columns[currentCol] * 0.75 / (d.fs || 10.5)) * 2)
          }
          if (cs > item.c) {
            data.config.merge[`${item.r}-${item.c}`] = {
              r: item.r,
              c: item.c,
              rs: item.r + 1,
              cs: cs + 1
            }
          }
        }
      }
    })
    // 处理单元格的边框
    if (data.config.borderInfo) {
      data.config.borderInfo.forEach(border => {
        if (border.borderType == 'border-all' || border.borderType == 'border-outside') {
          let maxRow = border.range[0].row[1] + 1
          let maxCol = border.range[0].column[1] + 1
          let startRow = border.range[0].row[0]
          let startCol = border.range[0].column[0]
          let color = convertToFullColorCode(border.color)
          let leftBorder = border.style || 1
          let topBorder = border.style || 1
          for (let i = startRow; i <= maxRow; i++) {
            for (let j = startCol; j <= maxCol; j++) {
              let leftBorderColor = ''
              let topBorderColor = ''
              if (border.borderType == 'border-outside') {
                if ((i == startRow || i == maxRow) && j != maxCol) {
                  topBorderColor = color
                }
                if ((j == startCol || j == maxCol) && i != maxRow) {
                  leftBorderColor = color
                }
              } else {
                if (j == maxCol || i == maxRow) {
                  if (j == maxCol && i != maxRow) {
                    leftBorderColor = color
                    topBorderColor = ''
                  } else if (i == maxRow && j != maxCol) {
                    topBorderColor = color
                    leftBorderColor = ''
                  } else {
                    leftBorderColor = ''
                    topBorderColor = ''
                  }
                } else {
                  leftBorderColor = color
                  topBorderColor = color
                }
              }
              if (leftBorderColor || topBorderColor) {
                let index = data.celldata.findIndex(item => item.r == i && item.c == j)
                if (index >= 0) {
                  data.celldata[index].v.border = {
                    leftBorderColor,
                    topBorderColor,
                    leftBorder,
                    topBorder
                  }
                } else {
                  data.celldata.push({
                    r: i,
                    c: j,
                    v: {
                      border: {
                        leftBorderColor,
                        topBorderColor,
                        leftBorder,
                        topBorder
                      }
                    }
                  })
                }
              }
            }
          }
        } else if (border.rangeType == 'cell') {
          let config = border.value
          let row = config.row_index
          let col = config.col_index
          let color = '#000000'
          let topBorder = 1
          let leftBorder = 1
          let leftBorderColor = ''
          if (config.l) {
            let index = data.celldata.findIndex(item => item.r == row && item.c == col)
            let color = config.l.color
            if (color.indexOf('rgb') != -1) {
              let reg = /([0-9]+)/g
              let arr = color.match(reg)
              color = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
            } else if (color.indexOf('#') != -1) {
              color = convertToFullColorCode(color)
            }
            leftBorderColor = color
            leftBorder = config.l.style
            if (index >= 0) {
              let cellItem = data.celldata[index]
              if (cellItem.v.border) {
                cellItem.v.border = {
                  ...cellItem.v.border,
                  leftBorder,
                  leftBorderColor: color
                }
              } else {
                cellItem.v.border = {
                  leftBorder,
                  leftBorderColor: color
                }
              }
            } else {
              data.celldata.push({
                r: row,
                c: col,
                v: {
                  border: {
                    leftBorder,
                    leftBorderColor: color
                  }
                }
              })
            }
          }
          if (config.r) {
            let index = data.celldata.findIndex(item => item.r == row && item.c == col + 1)
            let color = config.r.color
            leftBorder = config.r.style
            if (color.indexOf('rgb') != -1) {
              let reg = /([0-9]+)/g
              let arr = color.match(reg)
              color = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
            } else if (color.indexOf('#') != -1) {
              color = convertToFullColorCode(color)
            }
            color = convertToFullColorCode(config.r.color)
            if (index >= 0) {
              let cellItem = data.celldata[index]
              if (cellItem.v.border) {
                cellItem.v.border = {
                  ...cellItem.v.border,
                  leftBorder,
                  leftBorderColor: color
                }
              } else {
                cellItem.v.border = {
                  leftBorder,
                  leftBorderColor: color
                }
              }
            } else {
              data.celldata.push({
                r: row,
                c: col + 1,
                v: {
                  border: {
                    leftBorder,
                    leftBorderColor: color
                  }
                }
              })
            }
          }
          if (config.t) {
            let index = data.celldata.findIndex(item => item.r == row && item.c == col)
            let color = config.t.color
            if (color.indexOf('rgb') != -1) {
              let reg = /([0-9]+)/g
              let arr = color.match(reg)
              color = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
            } else if (color.indexOf('#') != -1) {
              color = convertToFullColorCode(color)
            }
            topBorderColor = color
            topBorder = config.t.style
            if (index >= 0) {
              let cellItem = data.celldata[index]
              if (cellItem.v.border) {
                cellItem.v.border = {
                  ...cellItem.v.border,
                  topBorder,
                  topBorderColor: color
                }
              } else {
                cellItem.v.border = {
                  topBorder,
                  topBorderColor: color
                }
              }
            } else {
              data.celldata.push({
                r: row,
                c: col,
                v: {
                  border: {
                    topBorder,
                    topBorderColor: color
                  }
                }
              })
            }
          }
          if (config.b) {
            let index = data.celldata.findIndex(item => item.r == row + 1 && item.c == col)
            let color = config.b.color
            if (color.indexOf('rgb') != -1) {
              let reg = /([0-9]+)/g
              let arr = color.match(reg)
              color = rgbToHex(Number(arr[0]), Number(arr[1]), Number(arr[2]))
            } else if (color.indexOf('#') != -1) {
              color = convertToFullColorCode(color)
            }
            topBorderColor = color
            topBorder = config.b.style
            if (index >= 0) {
              let cellItem = data.celldata[index]
              if (cellItem.v.border) {
                cellItem.v.border = {
                  ...cellItem.v.border,
                  topBorder: topBorder,
                  topBorderColor: color
                }
              } else {
                cellItem.v.border = {
                  topBorder: topBorder,
                  topBorderColor: color
                }
              }
            } else {
              data.celldata.push({
                r: row + 1,
                c: col,
                v: {
                  border: {
                    topBorder: topBorder,
                    topBorderColor: color
                  }
                }
              })
            }
          }
        }
      })
    }
    data.celldata.forEach(item => {
      let d = item.v
      let font = { charSet: 134 }
      // 字体是否加粗
      if (!d.bl) {
        font.weight = '400'
      } else {
        font.weight = '700'
      }
      // 字体
      if (!d.ff) {
        font.faceName = 'Times New Roman'
        // if (d.ff == 0) {
        //     font.faceName = 'Times New Roman'
        // } else {
        //     font.faceName = 'Microsoft YaHei UI'
        // }
      } else {
        switch (d.ff) {
          case 1:
            font.faceName = 'Arial'
            break
          case 2:
            font.faceName = 'Tahoma'
            break
          case 3:
            font.faceName = 'Verdana'
            break
          case 4:
            font.faceName = 'Microsoft YaHei UI'
            break
          case 5:
            font.faceName = 'Song'
            break
          case 6:
            font.faceName = 'ST Heiti'
            break
          case 7:
            font.faceName = 'ST Kaiti'
            break
          case 8:
            font.faceName = 'ST FangSong'
            break
          case 9:
            font.faceName = 'ST Song'
            break
          case 10:
            font.faceName = '华文新魏'
            break
          case 11:
            font.faceName = '华文行楷'
            break
          case 12:
            font.faceName = '华文隶书'
            break
        }
      }
      // 字体大小
      font.height = dealFontSize(d.fs)
      // if (!d.fs) {
      //     font.height = -14
      // } else {
      //     font.height = `-${d.fs}`
      // }
      // 删除线
      if (d.cl) {
        font.strikeOut = 1
      }
      // 下划线
      if (d.un) {
        font.underline = 1
      }
      // 是否斜体
      if (d.it) {
        font.italic = 1
      }
      let needPush = true
      fonts.forEach((ele, index) => {
        let count = 0
        let keys = Object.keys(ele)
        keys.forEach(key => {
          if (ele[key] == font[key]) {
            count++
          }
        })
        if (count == keys.length) {
          needPush = false
          // obj[item.r + '-' + item.c] = index
          obj[item.r + '-' + item.c] = dealTD(item, index)
        }
      })
      if (needPush) {
        fonts.push(font)
        // obj[item.r + '-' + item.c] = fonts.length - 1
        obj[item.r + '-' + item.c] = dealTD(item, fonts.length - 1)
      }
    })
    // console.log(obj)

    // 绘制相应的字体格式
    let $FONTS = '\t\t<Fonts>'
    fonts.forEach(item => {
      // let $FONT = `\t\t\t<Font faceName="${item.faceName}" charSet="134" height="${item.height}" weight="${item.weight}"`
      let $FONT = '\n\t\t\t<Font '
      for (ele in item) {
        if (item.hasOwnProperty(ele)) $FONT += `${ele}="${item[ele]}" `
      }
      $FONT += '/>'
      $FONTS += $FONT
    })
    $FONTS += '\n\t\t</Fonts>'

    $XML += $FONTS

    // 开始绘制表格
    let $TABLE = '\n\t\t<Table>'
    let $COL = ''
    columns.forEach(item => {
      $COL += `\n\t\t\t<COL width="${item}" />`
    })
    $COL += '\n\t\t\t<COL width="15" />\n'
    $TABLE += $COL
    let $TRS = ''
    for (let i = 0; i <= rows.length; i++) {
      // if (i == rows.length) rows[i] = 15
      let $TR = `\t\t\t<TR height="${rows[i] ? rows[i] : 15}" sequence="${i}">\n`
      for (j = 0; j <= columns.length; j++) {
        if (obj[i + '-' + j]) {
          $TR += '\t\t\t\t' + obj[i + '-' + j] + '\n'
        }
        if (j == columns.length) {
          $TR += `\t\t\t\t<TD col="${columns.length}" topBorder="0" />\n`
        }
        if (i == rows.length && j != columns.length) {
          $TR += `\t\t\t\t<TD col="${j}" leftBorder="0" />\n`
        }
      }
      $TR += '\t\t\t</TR>\n'
      $TRS += $TR
    }
    $TABLE += $TRS
    $TABLE += '\t\t</Table>'

    $XML += $TABLE

    // 合并单元格
    if (data.config.merge) {
      let $MERGES = '\n\t\t<Merges>'
      for (item in data.config.merge) {
        if (data.config.merge.hasOwnProperty(item)) {
          let ele = data.config.merge[item]
          $MERGES += `\n\t\t\t<Range row1="${ele.r}" col1="${ele.c}" row2="${ele.rs - 1}" col2="${ele.cs - 1}" />`
        }
      }
      $MERGES += '\n\t\t</Merges>'
      $XML += $MERGES
    }
    /*
        固定表头参数详解
            headerRows 固定在表头 Number 固定在表头第几行
            footerRows 固定在表尾 Number 固定在表尾第几行
            leftCols 固定在左侧 Number 固定在左侧第几列
            rightCols 固定在右侧 Number 固定在右侧第几列
            leftColsWhenLandscapePaging 固定在左侧（横向打印时） Number 固定在左侧第几列
            FixedHeaderRowsAsLeftPage 固定在右侧（横向打印时） Number 固定在右侧第几列
    */
    // 打印配置项
    /*
      Paper 纸张设置
        <Paper scale="40">
            <Margin left="19" top="25" right="19" bottom="25" />
        </Paper>
        scale 缩放比例
        left左边距
        top上边距
        right右边距
        bottom下边距
    */
    // 打印配置项
    let $PRINTPAGE = '\n\t\t<PrintPage>\n'
    if (data.paper) {
      let scale = data.paper.scale ? ` scale="${data.paper.scale}"` : ''
      let left = data.paper.left ? `left="${data.paper.left}"` : 'left="19"'
      let top = data.paper.top ? `top="${data.paper.top}"` : 'top="25"'
      let right = data.paper.right ? `right="${data.paper.right}"` : 'right="19"'
      let bottom = data.paper.bottom ? `bottom="${data.paper.bottom}"` : 'bottom="25"'
      $PRINTPAGE += `\t\t\t<Paper${scale}>\n`
      $PRINTPAGE += `\t\t\t\t<Margin ${left} ${top} ${right} ${bottom} />\n`
      $PRINTPAGE += '\t\t\t</Paper>\n'
    } else {
      $PRINTPAGE += '\t\t\t<Paper>\n'
      $PRINTPAGE += '\t\t\t\t<Margin left="19" top="25" right="19" bottom="25" />\n'
      $PRINTPAGE += '\t\t\t</Paper>\n'
    }
    $PRINTPAGE += '\t\t\t<Page islgnoreValidBorder="false">\n'
    if (data.pageBreak) {
      let $PAGEBREAK = '\t\t\t\t<Page-break>\n'
      $PAGEBREAK += '\t\t\t\t\t<FixedRowCols '
      for (ele in data.pageBreak) {
        $PAGEBREAK += `${ele}=${data.pageBreak[ele]} `
      }
      $PAGEBREAK += '/>\n'
      $PAGEBREAK += '\t\t\t\t</Page-break>\n'
      $PRINTPAGE += $PAGEBREAK
    }
    $PRINTPAGE += '\t\t\t\t<PageCode>\n'
    $PRINTPAGE += '\t\t\t\t\t<Font faceName="Microsoft YaHei UI" charSet="134" height="-14" weight="400" />\n'
    $PRINTPAGE += '\t\t\t\t</PageCode>\n'
    $PRINTPAGE += '\t\t\t</Page>\n'
    $PRINTPAGE += '\t\t</PrintPage>\n'

    $XML += $PRINTPAGE
    $XML += '\t</Workbook>\n'
    $XML += '</Report>'
    return $XML
  }


</script>

</html>
